using System.IO;
using System.Net;
using HtmlAgilityPack;

namespace mock_ehr_lib.Data.LookupServices
{
    public class CPTLookupService : ILookupService
    {
        private const string AmaUrlFormat =
            "https://ocm.ama-assn.org/OCM/CPTRelativeValueSearchResults.do?locality=63&keyword={0}";

        private const string DescriptionXPath = "//table/tbody/tr[1]/td[2]";
        private static CPTLookupService _instance;

        private CPTLookupService(){}
        public static CPTLookupService Instance { get { return _instance ?? (_instance = new CPTLookupService()); } }

        public string GetDescriptionByCode(string cptCode)
        {
            var amaUrl = string.Format(AmaUrlFormat, cptCode);
            var webClient = new WebClient();
            var result = webClient.DownloadString(amaUrl);
            var doc = new HtmlDocument();
            doc.Load(new StringReader(result));
            var nodeList = doc.DocumentNode.SelectNodes(DescriptionXPath);
            if(nodeList != null && nodeList.Count > 0)
            {
                var firstNode = nodeList[0];
                return firstNode.FirstChild.InnerText.Replace("<br />", "").Replace("\r", "").Replace("\n", "").Replace("\t", "");
            }
            return null;
        }
    }
}